<?php

namespace App\Services;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use Illuminate\Support\Facades\Log;

class SmsService
{
    public static function send(string $phone, array $param, string $signName, string $template_code, $type): bool
    {
        if($type == 1){
            $key_id = env('ALIBABA_CLOUD_ACCESS_KEY_ID');
            $key = env('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
        }else if($type == 2){
            $key_id = env('ALIBABA_CLOUD_ACCESS_KEY_ID_TWO');
            $key = env('ALIBABA_CLOUD_ACCESS_KEY_SECRET_TWO');
        }
        Log::channel('SendSms') -> info($phone.'key是: ',['key_id'=>$key_id,'key'=>$key]);
        AlibabaCloud::accessKeyClient(
            $key_id,
            $key
        )->regionId('cn-hangzhou')->asDefaultClient();

        try {
            $res = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers'  => $phone,
                        'SignName'      => $signName,
                        'TemplateCode'  => $template_code,
                        'TemplateParam' => !$param ? null : json_encode($param),
                    ],
                ])
                ->request();
            $res = json_decode($res,true);
            Log::channel('SendSms') -> info($phone.'短信发送结果: ',$res);
            if($res['Code'] == 'OK'){
                return true;
            }else{
                return false;
            }
        } catch (ClientException $e) {
            Log::channel('SendSms') -> info($phone.'短信发送失败: '.$e->getErrorMessage());
            return false;
        }
    }
}

